package com.yzx.lifeassistants.adapter;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.yzx.lifeassistants.R;
import com.yzx.lifeassistants.bean.Book;

/**
 * @Description: 图书列表适配器
 * @author: yzx
 * @time: 2016-3-8 下午1:34:00
 */
public class BookAdapter extends BaseAdapter {

	private List<Book> dataList;
	private Book data;
	private LayoutInflater inflater;
	private ViewHolder holder;

	public BookAdapter(Context context, List<Book> dataList) {
		this.dataList = dataList;
		this.inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		return dataList.size();
	}

	@Override
	public Object getItem(int position) {
		return dataList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (null == convertView) {
			convertView = inflater.inflate(R.layout.item_book_list, parent,
					false);
			holder = new ViewHolder();
			holder.nameTV = (TextView) convertView
					.findViewById(R.id.item_book_name);
			holder.authorTV = (TextView) convertView
					.findViewById(R.id.item_book_author);
			holder.publisherTV = (TextView) convertView
					.findViewById(R.id.item_book_publisher);
			holder.amountTV = (TextView) convertView
					.findViewById(R.id.item_book_amount);
			holder.placeTV = (TextView) convertView
					.findViewById(R.id.item_book_place);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		data = dataList.get(position);
		holder.nameTV.setText(data.getName());
		holder.authorTV.setText("作者：" + data.getAuthor());
		holder.publisherTV.setText("出版社：" + data.getPublisher());
		holder.amountTV.setText("年份：" + data.getYear() + " "
				+ addSpace(data.getAmount()));
		holder.placeTV.setText("位置：" + data.getPlace());
		return convertView;
	}

	static class ViewHolder {
		TextView nameTV;// 书名
		TextView authorTV;// 作者
		TextView publisherTV;// 出版社
		TextView amountTV;// 藏书数
		TextView placeTV;// 地点
	}

	/**
	 * 
	 * @Description: 在第一个数字后面加空格
	 */
	private String addSpace(String amount) {
		Matcher matcher = Pattern.compile("[0-9]").matcher(amount);
		if (matcher.find()) {
			amount = amount.substring(0, matcher.start() + 1) + " "
					+ amount.substring(matcher.start() + 1, amount.length());
		}
		return amount;
	}
}
